package cool.taomu.toolkit.oltu.controller

import cool.taomu.toolkit.oltu.service.Authorization
import cool.taomu.toolkit.oltu.service.OAuth2ServerService
import io.swagger.annotations.Api
import javax.inject.Inject
import javax.servlet.http.HttpServletRequest
import javax.ws.rs.GET
import javax.ws.rs.HeaderParam
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.Produces
import javax.ws.rs.QueryParam
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import org.slf4j.LoggerFactory
import javax.inject.Named

@Path("oauth")
@Api(value="OAuth2Controller", tags=#["OAuth2.0"])
class OAuth2Controller {
	val static LOG = LoggerFactory.getLogger(OAuth2Controller);

	@Inject
	Authorization auth;

	@Inject
	@Named("taomu.oauth2.table")
	String referer

	@GET
	@Path("/authorize/{responseType}/{clientId}/{clientSecret}")
	@Produces(MediaType.APPLICATION_JSON)
	def Response authorize(
		@HeaderParam("referer") String referer,
		@PathParam("responseType") String responseType,
		@PathParam("clientId") String clientId,
		@PathParam("clientSecret") String clientSecret
	) {
		var configReferer = this.referer
		if (configReferer !== null && !referer.equals(configReferer)) {
			return Response.status(404).build();
		}
		return OAuth2ServerService.authorize(responseType, clientId, clientSecret, auth)
	}

	@GET
	@Path("/token/{grantType}/{clientId}/{clientSecret}")
	@Produces(MediaType.APPLICATION_JSON)
	def Response token(@HeaderParam("referer") String referer, @HeaderParam("code") String code,
		@PathParam("grantType") String grantType, @PathParam("clientId") String clientId,
		@PathParam("clientSecret") String clientSecret) {
		var configReferer = this.referer
		if (configReferer !== null && !referer.equals(configReferer)) {
			return Response.status(404).build();
		}
		return OAuth2ServerService.token(code, grantType, clientId, clientSecret, "", auth)
	}

	@GET
	@Path("/token/{grantType}/{clientId}/{clientSecret}/{refreshToken}")
	@Produces(MediaType.APPLICATION_JSON)
	def Response token(@HeaderParam("referer") String referer, @HeaderParam("code") String code,
		@PathParam("grantType") String grantType, @PathParam("clientId") String clientId,
		@PathParam("clientSecret") String clientSecret, @PathParam("refreshToken") String refreshToken) {
		var configReferer = this.referer
		if (configReferer !== null && !referer.equals(configReferer)) {
			return Response.status(404).build();
		}
		return OAuth2ServerService.token(code, grantType, clientId, clientSecret, refreshToken, auth)
	}

	@GET
	@Path("/callback")
	@Produces(MediaType.APPLICATION_JSON)
	def Response callback(@QueryParam("code") String code, @Context HttpServletRequest request) {
		System.err.println(code)
		return Response.ok().build();
	}

}
